import React, {useCallback, useEffect, useState} from "react";
import {ApplicationEntity} from "../../entity/Application";
import {Button} from "antd";
import {PauseCircleOutlined, PlayCircleOutlined} from "@ant-design/icons";
import "./App.less";
import request from "@/utils/request";
import API from "@/utils/api";

const App: React.FC<ApplicationEntity> = (props) => {
    const [state, setState] = useState(false);
    const requestState = useCallback(() => {
        request<{ running: boolean }>(API.STATE_APPLICATION, {params: {id: props.id}}).then(res => {
            console.log(res.data);
            setState(res.data.running);
        });
    }, []);
    useEffect(() => {
        requestState();
        const inter = setInterval(() => {
            requestState()
        }, 30000);
        return () => {
            if (inter) {
                clearInterval(inter);
            }
        };
    }, [requestState]);
    const start = useCallback(() => {
        if (!state) {
            request<{ done: boolean }>(API.START_APPLICATION, {params: {id: props.id}}).then(res => {
                if (res.data.done) {
                    setState(true);
                }
            });
        } else {
            request(API.PAUSE_APPLICATION, {params: {id: props.id}}).then(res => {
                if (res.data.done) {
                    setState(false);
                }
            });

        }
    }, [state]);
    return (
        <div className='app-item'>
            <img src={props.image} alt='header'/>
            <div className='names'>
                <div>{props.name}</div>
                <div>{props.description}</div>
            </div>
            <p>
                {props.version}
            </p>
            <p>
                {props.effectiveDate}
            </p>
            <div className='button'>
                <Button onClick={start} size='large'>
                    {state ? <PauseCircleOutlined/> : <PlayCircleOutlined/>}
                    <div style={{display: "inline-block", marginLeft: "4px"}}>
                        {state ? "停止" : "运行"}
                    </div>
                </Button>
            </div>
        </div>
    );
};

export default App;
